<template>
	<view class="page">
		<!-- 顶部背景与导航 -->
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill" />
		<u-navbar :title="this.taskID ? '经济林种植面积审批' : '经济林种植面积上报'" :autoBack="true" leftIconColor="#fff"
			bgColor="transparent" :titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder />

		<view class="content">
			<view class="form-card">
				<view class="form-item">
					<text class="label">行政区划</text>
					<view class="ctrl full">
						<view class="picker-trigger" @click="openRegionPicker">
							<text v-if="!form.regionText" class="placeholder">请选择行政区划</text>
							<text v-else>{{ form.regionText }}</text>
							<u-icon name="arrow-down" size="18" color="#64748b" />
						</view>
					</view>
				</view>

				<view class="form-item">
					<text class="label">树种</text>
					<view class="ctrl full">
						<uni-data-select v-model="form.species" :localdata="speciesOpts" placeholder="请选择树种" />
					</view>
					<!-- uView 级联行政区划选择器 -->
					<u-picker :show="regionPickerShow" :columns="regionColumns" @confirm="onRegionConfirm"
						@cancel="regionPickerShow = false" @change="onRegionPickerChange" closeOnClickOverlay />
				</view>

				<view class="form-item">
					<text class="label">种植面积（亩）</text>
					<view class="ctrl num">
						<button class="btn-square" @click="dec('areaPlant')">－</button>
						<view class="num-display">{{ form.areaPlant }}</view>
						<button class="btn-square" @click="inc('areaPlant')">＋</button>
					</view>
				</view>

				<view class="form-item">
					<text class="label">间作面积（亩）</text>
					<view class="ctrl num">
						<button class="btn-square" @click="dec('areaInter')">－</button>
						<view class="num-display">{{ form.areaInter }}</view>
						<button class="btn-square" @click="inc('areaInter')">＋</button>
					</view>
				</view>

				<view class="form-item">
					<text class="label">年度</text>
					<view class="ctrl full">
						<picker mode="date" fields="year" :value="yearValue" @change="onYearChange">
							<view class="picker-input">
								<u-icon name="calendar" color="#29a74d" size="18" class="ico" />
								<text v-if="!form.year" class="placeholder">请选择年度</text>
								<text v-else>{{ form.year }}</text>
							</view>
						</picker>
					</view>
				</view>
			</view>

			<!-- 审批表单控件区域 -->
			<view v-if="formControls.length > 0" class="form-card approval-section">
				<view v-for="control in formControls" :key="control.controlId" class="form-item approval-item">
					<text class="label">{{ control.controlLabel }}</text>
					<view class="w-500">
						<!-- 文本域控件 -->
						<view v-if="control.controlType === 'textarea'">
							<textarea v-model="control.controlValue" :placeholder="`请输入${control.controlLabel}`"
								class="textarea-input" :disabled="!taskID"></textarea>
						</view>

						<!-- 单选框控件 -->
						<view v-else-if="control.controlType === 'radio'">
							<radio-group @change="onApprovalChange(control, $event)">
								<label v-for="(option, optIndex) in control.options" :key="optIndex">
									<radio :value="String(optIndex)"
										:checked="parseInt(control.controlValue) === optIndex" :disabled="!taskID" />
									<text class="radio-text">{{ option }}</text>
								</label>
							</radio-group>
						</view>

						<!-- 其他控件类型 -->
						<view v-else class="approval-other">
							<input v-model="control.controlValue" :placeholder="`请输入${control.controlLabel}`"
								class="input-field" :disabled="!taskID" />
						</view>
					</view>
				</view>
			</view>

			<view class="actions" v-if="!this.taskID">
				<button class="btn primary" @click="onSubmit">提交</button>
				<button class="btn ghost" @click="onDraft">存草稿</button>
				<button class="btn gray" @click="onReset">重置</button>
			</view>
			<view @tap="submit()" class="w-690 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
				style="bottom: 68rpx;left: 30rpx;" v-if="this.taskID">
				确认
			</view>
		</view>
	</view>
</template>

<script>
import { submitEconomicForestArea, getTreeSpeciesList, getDeptList } from '@/api/economicforest'
import { formDataShow, formDataSave, getAcreageInfo } from '@/api/sylin/index'
import navbarMixin from '@/common/navbarMixin'
export default {
	mixins: [navbarMixin],
	data() {
		return {
			form: {
				regionValue: [],
				regionText: '',
				species: '',
				areaPlant: 0,
				areaInter: 0,
				year: ''
			},
			regionPickerShow: false,
			regionColumns: [[], [], []],
			regionData: [],
			pIndex: 0,
			cIndex: 0,
			loadingCities: false,
			loadingDists: false,
			speciesOpts: [],
			taskID: '',
			formControls: [], // 存储解析后的表单控件数据
			userSelectedLevel: 1 // 记录用户实际选择的层级
		}
	},
	computed: {
		yearValue() {
			return this.form.year ? `${this.form.year}-01-01` : ''
		}
	},
	onLoad() {
		// 接收参数
		this.taskID = this.$route.query.taskID
		this.getTreeSpeciesList()
		this.getDeptList()
		this.getAcreageInfo()
		this.getTaskData()
	},
	methods: {
		getAcreageInfo() {
			getAcreageInfo(this.taskID).then(res => {
				this.form.areaPlant = res.data.acreagePlant
				this.form.areaInter = res.data.acreageInterplant
				this.form.year = res.data.year
				this.form.regionValue = res.data.deptId
				this.form.regionText = res.data.compartment
				this.form.species = res.data.treeSpeciesId
				this.form.remark = res.data.remark
				this.form.regionValue = res.data.deptId
			})
		},
		// 提交
		submit() {
			// 检查必要参数
			if (!this.taskID) {
				uni.showToast({ title: '任务ID不存在', icon: 'none' })
				return
			}

			if (!this.formControls || this.formControls.length === 0) {
				uni.showToast({ title: '没有审批数据', icon: 'none' })
				return
			}

			// 参考PC端实现，直接传递对象数组
			const formData = this.formControls.map(control => {
				return {
					controlId: control.controlId,
					controlType: control.controlType,
					controlLable: control.controlLabel, // 注意：PC端用的是controlLable
					controlIsParam: control.controlValue || '', // 使用controlValue作为controlIsParam
					controlValue: control.controlValue || '',
					controlDefault: control.controlDefault || ''
				}
			})

			console.log('提交参数:', {
				taskID: this.taskID,
				formData: formData
			})

			uni.showLoading({ title: '提交中...' })

			formDataSave(this.taskID, formData).then(res => {
				uni.hideLoading()
				console.log('提交响应:', res)
				if (res && res.code === 200) {
					uni.showToast({ title: '提交成功', icon: 'success' })
					// 可以添加页面跳转或其他操作
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({ title: '请先签收' || '提交失败', icon: 'none' })
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('提交失败:', err)
				uni.showToast({ title: '提交失败: ' + ('请先签收'), icon: 'none' })
			})
		},
		// 获取审批行数据
		getTaskData() {
			// 只有当taskID存在且有效时才调用API
			if (!this.taskID) {
				console.log('无taskID，跳过获取任务数据')
				return
			}
			formDataShow(this.taskID).then(res => {
				console.log(res, 'res')
				// 处理审批行数据
				if (res && res.code === 200 && res.data && Array.isArray(res.data)) {
					this.parseFormData(res.data)
				}
			}).catch(err => {
				console.error('获取任务数据失败:', err)
				uni.showToast({ title: '获取任务数据失败', icon: 'none' })
			})
		},
		// 解析审批行数据
		parseFormData(formDataArray) {
			try {
				const formControls = []

				formDataArray.forEach(item => {
					// 解析格式: "FormProperty_xxx--__!!controlType--__!!controlLabel--__!!controlValue--__!!controlDefault"
					const parts = item.split('--__!!')
					if (parts.length >= 4) {
						const controlId = parts[0] // FormProperty_xxx
						const controlType = parts[1] // textarea, radio, etc.
						const controlLabel = parts[2] // 批注, 审批意见, etc.
						let controlValue = parts[3] // f, i, etc.
						const controlDefault = parts[4] || '' // null, 同意--__--不同意, etc.

						// 处理 controlValue 中的 null 值
						if (controlValue === 'null' || controlValue === 'f__!!null') {
							controlValue = ''
						}

						const control = {
							controlId,
							controlType,
							controlLabel,
							controlValue,
							controlDefault
						}

						// 如果是radio类型，解析选项
						if (controlType === 'radio' && controlDefault) {
							control.options = controlDefault.split('--__--').filter(opt => opt.trim())
						}

						formControls.push(control)
					}
				})

				console.log('解析后的表单控件:', formControls)
				this.formControls = formControls

				// 根据控件类型填充表单
				this.fillFormFromControls(formControls)

			} catch (err) {
				console.error('解析审批行数据失败:', err)
			}
		},
		// 根据控件数据填充表单
		fillFormFromControls(controls) {
			controls.forEach(control => {
				switch (control.controlLabel) {
					case '批注':
						// 如果有批注字段，可以存储到备注中
						this.form.remark = control.controlValue
						break
					case '审批意见':
						// 审批意见通常是radio类型
						if (control.controlType === 'radio') {
							this.form.approvalResult = control.controlValue
						}
						break
					// 可以根据实际需要添加更多字段映射
				}
			})
		},
		// 审批控件值改变事件
		onApprovalChange(control, event) {
			const selectedValue = event.detail.value
			// 确保存储的是字符串类型，与后端数据格式一致
			control.controlValue = String(selectedValue)
			console.log('审批控件值改变:', control.controlLabel, selectedValue)
		},
		// 获取控件值（用于显示当前选中的值）
		getControlValue(control) {
			// 处理空值情况
			if (!control.controlValue || control.controlValue === 'null' || control.controlValue === 'f__!!null') {
				return ''
			}

			if (control.controlType === 'radio') {
				// 对于radio类型，返回选中的选项文本
				const selectedIndex = parseInt(control.controlValue)
				if (control.options && control.options[selectedIndex]) {
					return control.options[selectedIndex]
				}
				return control.controlValue
			}
			return control.controlValue
		},



		// 获取树种列表
		getTreeSpeciesList() {
			getTreeSpeciesList().then(res => {
				if (Array.isArray(res) && res.length) {
					this.speciesOpts = res.map(item => ({ text: item.label, value: item.value }))
				}
			}).catch(() => { })
		},
		// 获取行政区划列表并构建树
		getDeptList() {
			getDeptList().then(res => {
				const list = Array.isArray(res?.data) ? res.data : []
				if (list.length) this.buildRegionTree(list)
			}).catch(() => { })
		},
		buildRegionTree(deptList) {
			const topLevel = deptList.filter(item => item.parentId === 0)
			const buildTree = (parentId) => {
				return deptList
					.filter(item => item.parentId === parentId)
					.map(item => ({ label: item.deptName, value: item.deptId, children: buildTree(item.deptId) }))
			}
			this.regionData = topLevel.map(item => ({ label: item.deptName, value: item.deptId, children: buildTree(item.deptId) }))
		},
		openRegionPicker() {
			// 重置用户选择层级
			this.userSelectedLevel = 1
			// 首次打开先加载省份
			if (!this.regionColumns[0].length) {
				this.initRegionColumns()
			}
			this.regionPickerShow = true
		},
		initRegionColumns() {
			const provs = this.regionData.map(p => p.label)
			// 初始状态所有列都加"请选择"，让用户可以滚动
			this.regionColumns = [
				['请选择', ...provs],
				['请选择'],
				['请选择']
			]
		},
		onRegionPickerChange(e) {
			const col = e?.columnIndex ?? e?.detail?.column
			const idx = e?.index ?? e?.detail?.value
			if (col === 0) {
				// 第一列有"请选择"，所以索引需要减1
				this.pIndex = Math.max(0, (idx || 1) - 1)
				this.cIndex = 0
				this.userSelectedLevel = 1 // 用户选择了第一列
				// 占位，随后刷新
				this.regionColumns.splice(1, 2, ['加载中...'], ['请选择'])
				this.ensureCitiesFor(this.pIndex).then(() => this.ensureDistsFor(this.pIndex, 0))
			} else if (col === 1) {
				// 第二列有"请选择"，所以索引需要减1
				this.cIndex = Math.max(0, (idx || 1) - 1)
				this.userSelectedLevel = 2 // 用户选择了第二列
				this.regionColumns.splice(2, 1, ['加载中...'])
				this.ensureDistsFor(this.pIndex, this.cIndex)
			} else if (col === 2) {
				this.userSelectedLevel = 3 // 用户选择了第三列
			}
		},
		onRegionConfirm(e) {
			let vals = e?.value || []
			if (!Array.isArray(vals)) vals = [String(vals)]
			const clean = vals.filter(v => v && v !== '请选择' && v !== '加载中...')

			console.log('过滤后的值:', clean)

			// 反查编码 - 根据用户实际选择的层级来确定
			const regionValue = []
			const regionText = []

			// 第一列：省份 - 只有当用户真正选择了省份时才添加
			if (this.userSelectedLevel >= 1 && clean[0]) {
				const prov = this.regionData.find(p => p.label === clean[0])
				console.log('找到的省份:', prov)
				if (prov) {
					regionValue.push(prov.value)
					regionText.push(prov.label)

					// 第二列：城市 - 只有当用户真正选择了第二列时才添加
					if (this.userSelectedLevel >= 2 && clean[1] && prov.children) {
						const city = prov.children.find(c => c.label === clean[1])
						console.log('找到的城市:', city)
						if (city) {
							regionValue.push(city.value)
							regionText.push(city.label)

							// 第三列：区县 - 只有当用户真正选择了第三列时才添加
							if (this.userSelectedLevel >= 3 && clean[2] && city.children) {
								const dist = city.children.find(d => d.label === clean[2])
								console.log('找到的区县:', dist)
								if (dist) {
									regionValue.push(dist.value)
									regionText.push(dist.label)
								}
							}
						}
					}
				}
			}
			this.form.regionText = regionText.join('/')
			this.form.regionValue = regionValue.filter(Boolean)
			this.regionPickerShow = false
		},
		async ensureCitiesFor(pIdx) {
			const prov = this.regionData[pIdx]
			if (!prov) return
			if (prov.children && prov.children.length) {
				this.regionColumns.splice(1, 1, ['请选择', ...prov.children.map(c => c.label)])
				return
			}
			this.loadingCities = false
		},
		async ensureDistsFor(pIdx, cIdx) {
			const prov = this.regionData[pIdx]
			const city = prov?.children?.[cIdx]
			if (!city) {
				this.regionColumns.splice(2, 1, ['请选择'])
				return
			}
			if (city.children && city.children.length) {
				this.regionColumns.splice(2, 1, ['请选择', ...city.children.map(d => d.label)])
				return
			}
			this.loadingDists = false
		},
		onYearChange(e) {
			const y = String(e?.detail?.value || '').split('-')[0] || ''
			this.form.year = y
		},
		inc(key) {
			const val = Number(this.form[key] || 0)
			this.form[key] = this.toFixedNum(val + 1)
		},
		dec(key) {
			const val = Number(this.form[key] || 0)
			this.form[key] = this.toFixedNum(Math.max(0, val - 1))
		},
		toFixedNum(n) {
			return Number(parseFloat(n).toFixed(2))
		},
		onSubmit() {
			this.submitData(1)
		},
		onDraft() {
			this.submitData(0)
		},
		onReset() {
			this.form = {
				regionValue: [],
				regionText: '',
				species: '',
				areaPlant: 0,
				areaInter: 0,
				year: ''
			}
		},
		submitData(postFlag) {
			// 校验
			if (!this.form.regionValue.length) { uni.showToast({ title: '请选择行政区划', icon: 'none' }); return }
			if (!this.form.species) { uni.showToast({ title: '请选择树种', icon: 'none' }); return }
			if (!(this.form.areaPlant > 0)) { uni.showToast({ title: '请输入种植面积', icon: 'none' }); return }
			if (!(this.form.areaInter >= 0)) { uni.showToast({ title: '请输入间作面积', icon: 'none' }); return }
			if (!this.form.year) { uni.showToast({ title: '请选择年度', icon: 'none' }); return }

			// 组装树种名称
			const sel = (this.speciesOpts || []).find(i => i.value == this.form.species)
			const treeSpecies = sel ? sel.text : ''

			const payload = {
				acreagePlant: Number(this.form.areaPlant),
				acreageInterplant: Number(this.form.areaInter),
				year: this.form.year,
				postFlag,
				treeSpeciesId: this.form.species,
				treeSpecies: treeSpecies,
				compartment: this.form.regionText
			}
			uni.showLoading({ title: postFlag === 1 ? '提交中...' : '保存中...' })
			submitEconomicForestArea(payload).then(res => {
				uni.hideLoading()
				if (res && res.code === 200) {
					uni.showToast({ title: postFlag === 1 ? '提交成功' : '保存成功', icon: 'success' })
					if (postFlag === 1) this.onReset()
				} else {
					uni.showToast({ title: res?.msg || '操作失败', icon: 'none' })
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('上报失败:', err)
				uni.showToast({ title: '网络错误，请重试', icon: 'none' })
			})
		}
	}
}
</script>

<style lang="scss" scoped>
/* 绿色主题变量 */
$brand: #29a74d;
$brand-weak: #e9f7ee;
$brand-border: #cfe9db;
$brand-strong: #239243;

.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 180rpx;
	z-index: 2;
}

.page {
	background: #f6f7fb;
	min-height: 100vh;
}

.content {
	padding: 24rpx;
}

.form-card {
	background: #fff;
	border: 1rpx solid #eef2f7;
	border-radius: 22rpx;
	padding: 18rpx 18rpx;
	box-shadow: 0 10rpx 24rpx rgba(12, 18, 28, .06);
}

.form-item {
	display: flex;
	align-items: center;
	padding: 16rpx 8rpx;
}

.form-item+.form-item {
	border-top: 1rpx dashed #eef2f7;
}

.label {
	width: 220rpx;
	color: #374151;
	font-size: 28rpx;
}

.ctrl {
	flex: 1;
	display: flex;
	align-items: center;
	min-height: 72rpx;
}
.ctrl.full {
	width: 100%;
}
.picker-trigger {
	height: 72rpx;
	border: 1rpx solid $brand-border;
	border-radius: 14rpx;
	padding: 0 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: $brand-weak;
	color: #111827;
}

.picker-trigger .placeholder {
	color: #9ca3af;
}

/* 下拉与选择样式统一成绿色弱底 */
::v-deep .uni-select,
::v-deep .uni-stat__select .uni-select,
::v-deep .uni-data-tree .uni-select {
	height: 72rpx;
	min-height: 72rpx;
	border-radius: 14rpx;
	border-color: $brand-border;
	background: $brand-weak;
}

::v-deep .uni-select__input-text {
	line-height: 72rpx;
	font-size: 28rpx;
}

/* 年度选择外观 */
.picker-input {
	height: 72rpx;
	border: 1rpx solid $brand-border;
	border-radius: 14rpx;
	padding: 0 20rpx;
	display: flex;
	align-items: center;
	background: $brand-weak;
}

.picker-input .ico {
	margin-right: 10rpx;
}

.picker-input .placeholder {
	color: #9ca3af;
}

/* 数字加减控件 */
.ctrl.num {
	gap: 8rpx;
}

.btn-square {
	width: 72rpx;
	height: 56rpx;
	line-height: 56rpx;
	text-align: center;
	border-radius: 8rpx;
	background: #f3f4f6;
	color: #374151;
	border: 1rpx solid #e5e7eb;
	font-size: 32rpx;
}

.num-display {
	min-width: 120rpx;
	height: 56rpx;
	line-height: 56rpx;
	text-align: center;
	border-radius: 8rpx;
	background: #fff;
	border: 1rpx solid #e5e7eb;
	font-weight: 700;
	color: #111827;
}

/* 底部按钮 */
.actions {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 18rpx;
	padding: 26rpx 12rpx;
}

.btn {
	height: 68rpx;
	line-height: 68rpx;
	border-radius: 14rpx;
	font-size: 28rpx;
	border: none;
}

.btn.primary {
	background: linear-gradient(90deg, lighten($brand, 2%), $brand-strong);
	color: #fff;
	box-shadow: 0 6rpx 14rpx rgba(37, 154, 68, .22);
}

.btn.ghost {
	background: #fff;
	color: $brand-strong;
	box-shadow: inset 0 0 0 1rpx $brand-border;
}

.btn.gray {
	background: #e5e7eb;
	color: #374151;
}

/* 审批表单样式 */
.approval-section {
	margin-top: 24rpx;
}

.approval-item {
	border-top: 1rpx dashed #eef2f7;
}

.approval-item:first-child {
	border-top: none;
}

.textarea-input {
	width: 100%;
	min-height: 120rpx;
	padding: 16rpx;
	border: 1rpx solid $brand-border;
	border-radius: 14rpx;
	background: $brand-weak;
	font-size: 28rpx;
	color: #111827;
	resize: none;
}

.textarea-input:disabled {
	background: #f9fafb;
	color: #9ca3af;
}

.radio-item {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
	padding: 12rpx 16rpx;
	border-radius: 12rpx;
	background: #f9fafb;
	border: 1rpx solid #e5e7eb;
}

.radio-item:last-child {
	margin-bottom: 0;
}

.radio-text {
	margin-left: 12rpx;
	margin-right: 20rpx;
	font-size: 28rpx;
	color: #374151;
}

.radio-item:disabled {
	opacity: 0.6;
}

.approval-other {
	width: 100%;
}

.input-field {
	width: 100%;
	height: 72rpx;
	padding: 0 20rpx;
	border: 1rpx solid $brand-border;
	border-radius: 14rpx;
	background: $brand-weak;
	font-size: 28rpx;
	color: #111827;
}

.input-field:disabled {
	background: #f9fafb;
	color: #9ca3af;
}
</style>